
function Venue() {
    var prefs = new gadgets.Prefs();
    
    this.headingFontName = prefs.getString("heading_font-style");
    this.countFontName = prefs.getString("count_font-style");
    this.infoFontName = prefs.getString("info_font-style");
    this.layoutURL = prefs.getString("layoutURL") ? prefs.getString("layoutURL") : "http://c624743.r43.cf2.rackcdn.com/Default.xml";
    this.styleURL = prefs.getString("styleURL") ? prefs.getString("styleURL") : "http://c624743.r43.cf2.rackcdn.com/Default.css";
    
    //Other variables that the Gadget requires.
    this.mayor = new Object();
    this.counts = [];
    this.tips = [];
    this.specials = [];
    this.countsIndex = 0;
    this.tipsIndex = 0;
    this.specialsIndex = 0;
    this.rotateContentTimer = null;
    this.showTips = true;
    this.showSpecials = false;
    this.checkForUpdates = false;
    this.refreshInterval = 10000;
    this.tipsEnabled = false;
    this.specialsEnabled = false;
    this.tipsHeading = "";
    this.specialsHeading = "";
}
//Load the layout and CSS files.
Venue.prototype.loadLayout = function() {
    var params = {};
    var self = this;
    var link = $("<link>");
    
    //Load CSS file as specified in the Gadget settings.
    if (this.styleURL) {
	link.attr({
	    type: "text/css",
	    rel: "stylesheet",
	    href: this.styleURL
	});
	$("head").append(link);
    }
 
    if (this.layoutURL) {	
	params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.DOM;
	gadgets.io.makeRequest(this.layoutURL, function(obj) {
	    var data = obj.data;
	
	    if (data.getElementsByTagName("Layout").length == 0) {
		return;
	    }
	    
	    //Set the layout for the first page.
	    $("#container").html(data.getElementsByTagName("Layout")[0].childNodes[1].nodeValue);
	    
	    //Store the settings.
	    if (data.getElementsByTagName("Mayor").length > 0) {
		var mayor = data.getElementsByTagName("Mayor")[0];
		
		if (mayor.childNodes.length > 0) {
		    self.mayor.message = mayor.childNodes[1].childNodes[0].nodeValue;
		    self.mayor.noMayor = mayor.childNodes[3].childNodes[0].nodeValue;
		}
	    }
	    
	    if (data.getElementsByTagName("Checkins").length > 0) {
		var checkins = data.getElementsByTagName("Checkins")[0];
		
		if (checkins.childNodes.length > 0) {		    
		    if (checkins.getAttribute("enabled") == "true") {
			self.counts.push(new Stat("checkins", checkins.childNodes[1].childNodes[0].nodeValue));
		    }
		}
	    }
	    
	    if (data.getElementsByTagName("Users").length > 0) {
		var users = data.getElementsByTagName("Users")[0];
		
		if (users.childNodes.length > 0) {
		    if (users.getAttribute("enabled") == "true")
			self.counts.push(new Stat("users", users.childNodes[1].childNodes[0].nodeValue));
		}
	    }
	    
	    if (data.getElementsByTagName("HereNow").length > 0) {
		var hereNow = data.getElementsByTagName("HereNow")[0];
		
		if (hereNow.childNodes.length > 0) {
		    if (hereNow.getAttribute("enabled") == "true")
			self.counts.push(new Stat("hereNow", hereNow.childNodes[1].childNodes[0].nodeValue));
		}
	    }
 
	    if (data.getElementsByTagName("Tips").length > 0) {
		var tips = data.getElementsByTagName("Tips")[0];
		
		if (tips.childNodes.length > 0) {
		    self.tipsEnabled = tips.getAttribute("enabled");
		    self.tipsHeading = tips.childNodes[1].childNodes[0].nodeValue;
		}
	    }
	    
	    if (data.getElementsByTagName("Specials").length > 0) {
		var specials = data.getElementsByTagName("Specials")[0];
		
		if (specials.childNodes.length > 0) {
		    self.specialsEnabled = specials.getAttribute("enabled");
		    self.specialsHeading = specials.childNodes[1].childNodes[0].nodeValue;
		}
	    }
	    
	    self.applyStyle(self);
	}, params);
    }
}
//Style the Gadget.
Venue.prototype.applyStyle = function(self) {
    var prefs = new gadgets.Prefs();
    var css = document.createElement("style");
    var customFontUsed = false;
    var fontFace;
    
    css.type = "text/css";
    
    //Load custom fonts if necessary.
    if (customFontUsed) {
	document.getElementsByTagName("head")[0].appendChild(css);
    }
 
    //Tips and Specials styles
    $(".counts").addClass("count_font-style");
	$(".info").addClass("info_font-style");
    
    //Highlight color
    $(".firstName").css("color", prefs.getString("highlightColor"));
    $(".counts, .info, #header").css("background-color", prefs.getString("highlightColor"));
    
    self.getData();
}
Venue.prototype.getData = function() {
    gadgets.rpc.call('', 'rsparam_get', null, new gadgets.Prefs().getString("id"), "social:foursquare");
}
Venue.prototype.processData = function(self, name, value) {
    if (value) {
	var json = JSON.parse(value);
	
	self.token = json.access;
	
	if (json.displayLocation) {
	    self.venueID = json.displayLocation;
	}
	else {
	    self.venueID = json.companyLocation;
	}
	
	self.getVenue();
    }
    else {
	$("#container").empty();
	$("#container").append("<div class='error'>Please create a Foursquare Social Connection for your Company or Display before using this Gadget.</div>");
	readyEvent();
    }
}
//Get the venue details from the Foursquare API.
Venue.prototype.getVenue = function() {
    var params = {};
    var self = this;
    
    this.reset();
 
    params[gadgets.io.RequestParameters.CONTENT_TYPE] = gadgets.io.ContentType.JSON;
    params[gadgets.io.RequestParameters.REFRESH_INTERVAL] = 60;
    gadgets.io.makeRequest("https://api.foursquare.com/v2/venues/" + this.venueID + "?oauth_token=" + this.token,
	function(response) {
	    var i, j;
	    var firstName, lastName, photo;
	    var venue = response.data.response.venue;
	    var index = 0;
    	    
	    //Check for tips.
	    if (venue.tips.groups[0] && (self.tipsEnabled == "true")) {
		if (venue.tips.groups) {
		    for (i = 0; i < venue.tips.groups.length; i++) {		
			if (venue.tips.groups[i].items) {
			    for (j = 0; j < venue.tips.groups[i].items.length; j++) {		
				self.tips[index] = new Object();
				self.tips[index].text = venue.tips.groups[i].items[j].text;
				index++;
			    }
			}
		    }		    	    
		}
	    }
	    
	    //Check for specials.
	    if (self.specialsEnabled == "true") {
		for (i = 0; i < venue.specials.length; i++, j++) {		
		    self.specials[i] = new Object();
		    self.specials[i].text = venue.specials[i].message;
		}
	    }
	
	    //Check for mayor.
	    if (venue.mayor.user) {
		self.mayor.firstName = venue.mayor.user.firstName ? venue.mayor.user.firstName : "";
		self.mayor.photo = venue.mayor.user.photo ? venue.mayor.user.photo : "";
		self.mayor.count = venue.mayor.count;
	    }
	    
	    //Get counts.
	    if (venue.stats) {
		for (i = 0; i < self.counts.length; i++) {
		    if (self.counts[i].type == "checkins") {
			self.counts[i].count = venue.stats.checkinsCount ? venue.stats.checkinsCount : 0;
		    }
		    else if (self.counts[i].type == "users") {
			self.counts[i].count = venue.stats.usersCount ? venue.stats.usersCount : 0;
		    }
		}
	    }
	    
	    if (venue.hereNow) {
		for (i = 0; i < self.counts.length; i++) {
		    if (self.counts[i].type == "hereNow") {
			self.counts[i].count = venue.hereNow.count ? venue.hereNow.count : 0;
		    }
		}
	    }
	    
	    self.showContent();
	    setTimeout(function() { self.expireUpdatesTimer(self); }, 60000);
	}, params);
}
Venue.prototype.reset = function() {
    this.mayor.firstName = "";
    this.mayor.photo = "";
    this.mayor.count = 0;
    
    //Clear the count only.
    for (var i = 0; i <this.counts.length; i++) {
	this.counts[i].count = 0;
    }
 
    this.specials = [];
    this.tips = [];
}
Venue.prototype.showContent = function() {
    var $logo = $(".logo");
    var $photo = $(".photo");
    var $checkins = $(".checkins");
    var $foursquare = $(".foursquare");
    var $message = $(".message");
    var $firstName = $(".firstName");
    var $qrCode = $(".qrCode");
 
    //Configure logo.
    if (gadgets.Prefs().getBool("showLogo")) {
	$logo.attr("src", "http://c624743.r43.cf2.rackcdn.com/Logo.png");
    }
    else {
	//Remove it from the DOM so it doesn't take up space.
	$("#header").remove();
	$("#static").height("55%");
	$("#dynamic").height("45%");
    }
    
    //Configure QR Code.
    if (gadgets.Prefs().getBool("showQR")) {
	$qrCode.attr("src", "https://chart.googleapis.com/chart?cht=qr&chs=150x150&chl=" + encodeURIComponent("https://foursquare.com/mobile/venue/" + this.venueID));
    }
    else {
	//Remove it from the DOM so it doesn't take up space.
	$("#qr").remove();
    }

    if (this.mayor.count == 0) {	//No mayor.
	$message.html(this.mayor.noMayor);
    }
    else {
	$photo.attr("src", this.mayor.photo);
	$foursquare.attr("src", "http://c624743.r43.cf2.rackcdn.com/Foursquare.png");
	$checkins.html(this.mayor.count);	
	$message.html(this.mayor.message);
	$firstName.html(this.mayor.firstName);
    }
    
    this.rotateContent();
}
Venue.prototype.rotateContent = function() {
    var self = this;
    var $countsTitle = $("<div>");
    var $countsText = $("<p>");
    var $info = $("<div>");
    var $infoTitle = $("<div>");
    var $infoText = $("<p>");    
    var hasNoContent = $(".countsTitle").html() == "" ? true : false;
    var hasTips = this.tips.length > 0 ? true : false;
    var hasSpecials = this.specials.length > 0 ? true : false;
    
    if (this.checkForUpdates) {
	this.checkForUpdates = false;
	this.getData();
	return;
    }
    
    //Counts
    $countsTitle.addClass("countsTitle");
    $countsText.addClass("countsText");
    
    if (this.countsIndex >= this.counts.length) {
	this.countsIndex = 0;
    }
    
    if (this.counts.length > 0) {
	$countsTitle.html(this.counts[this.countsIndex].heading);
	$countsText.html(this.counts[this.countsIndex].count);
    }
    
    //Tips & Specials
    $infoTitle.addClass("infoTitle");
    $infoText.addClass("infoText");
    
    if (hasTips) {
	//Show Specials next since we've reached the end of the Tips.
	if (this.tipsIndex >= this.tips.length) {
	    this.tipsIndex = 0;
	    this.showTips = false;
	}
	else {
	    this.showTips = true;
	}
    }
    else {
	this.showTips = false;
    }
    
    if (hasSpecials) {
	if (this.specialsIndex >= this.specials.length) {
	    this.specialsIndex = 0;
	    this.showSpecials = false;
	}
	else {
	    this.showSpecials = true;
	}
    }
    else {
	this.showSpecials = false;
    }
    
    if (this.showTips) {
	this.showNextTip($infoTitle, $infoText);
    }
    else if (this.showSpecials) {
	this.showNextSpecial($infoTitle, $infoText);
    }
    else if (hasTips) {
	this.showNextTip($infoTitle, $infoText);
    }
    else if (hasSpecials) {
	this.showNextSpecial($infoTitle, $infoText);
    }

    if (hasNoContent) {	//Fade in content for the first time.	
	this.showCounts($countsTitle, $countsText);
	this.showInfo($infoTitle, $infoText);
    }
    else {	//Fade out old content before showing new content.
	//Counts
	$(".countsTitle").fadeOut("slow");
	$(".countsText").fadeOut("slow", function() {
	    self.showCounts($countsTitle, $countsText);
	});
	   
	//Tips & Specials
	$(".infoTitle").fadeOut("slow");
	$(".infoText").fadeOut("slow", function() {
	    self.showInfo($infoTitle, $infoText);
	    
	    rotateContentTimer = setTimeout(function() {
		self.rotateContent();
	    }, self.refreshInterval);
	});
    }
		    
    this.countsIndex++;
}
Venue.prototype.showNextTip = function($title, $text) {
    $title.html(this.tipsHeading);
    $text.html(this.tips[this.tipsIndex].text);
    this.tipsIndex++;
}
Venue.prototype.showNextSpecial = function($title, $text) {
    $title.html(this.specialsHeading);
    $text.html(this.specials[this.specialsIndex].text);
    this.specialsIndex++;
}
Venue.prototype.showCounts = function($title, $text) {
    var prefs = new gadgets.Prefs();
    var $titleParent = $(".countsTitle").parent();
    var $textParent = $(".countsText").parent();
    
    //Remove old counts.
    $(".countsTitle").remove();
    $(".countsText").remove();
    
    //Add new counts to DOM.
    $title.hide().prependTo($titleParent).fadeIn("slow");
    $text.hide().appendTo($textParent);
    
    //Apply styles now that element has been added to the DOM.
    $(".countsText").addClass("count_font-style");
    
    $text.fadeIn("slow");
}
Venue.prototype.showInfo = function($title, $text) {
    var $titleParent = $(".infoTitle").parent();
    var $textParent = $(".infoText").parent();
    
    //Remove old info.
    $(".infoTitle").remove();
    $(".infoText").remove();
    
    //Add new info to DOM and fade it in.
    $title.hide().prependTo($titleParent).fadeIn("slow");
    $text.hide().appendTo($textParent).fadeIn("slow", function() { readyEvent(); });
}
Venue.prototype.startContentTimer = function() {
    var self = this;
    
    rotateContentTimer = setTimeout(function() {
	self.rotateContent();
    }, self.refreshInterval);
}
Venue.prototype.stopContentTimer = function() {   
    clearTimeout(rotateContentTimer);
}
Venue.prototype.expireUpdatesTimer = function(self) {
    self.checkForUpdates = true;
}
function Stat(type, heading) {
    this.type = type;
    this.heading = heading;
}